package com.jacob.cloud.mall.common.exception;

import com.jacob.cloud.mall.common.common.ApiRestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 处理统一异常的handler
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 默认异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(Exception e) {
        log.error("Default Exception : ", e);
        return ApiRestResponse.error(MallExceptionEnum.SYSTEM_ERROR);
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(MallException.class)
    @ResponseBody
    public Object handleImoocMallException(MallException e) {
        log.error("MallException : ", e);
        return ApiRestResponse.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理请求参数校验异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public Object ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        log.error("ConstraintViolationException : ", e);
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(","));
        return ApiRestResponse.error(MallExceptionEnum.REQUEST_ARGUMENT_ERROR.getCode(), message);
    }

    // 处理请求参数格式错误 @RequestBody上validate失败后抛出的异常是BindException异常。
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Object BindExceptionHandler(BindException e) {
        log.error("BindException : ", e);
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
        return ApiRestResponse.error(MallExceptionEnum.REQUEST_ARGUMENT_ERROR.getCode(), message);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiRestResponse<Object> handlerMethodArgumentNoValidException(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException: "+e);
        return handlerBindingResult(e.getBindingResult());
    }

    /**
     * 将异常信息暴露给用户
     * @param result
     * @return
     */
    private ApiRestResponse<Object> handlerBindingResult(BindingResult result) {
        List<String> list = new ArrayList<>();
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError objectError : allErrors) {
                list.add(objectError.getDefaultMessage());
            }
        }
        System.out.println("error_list"+list);
        if (list.size() == 0) {
            return ApiRestResponse.error(MallExceptionEnum.REQUEST_ARGUMENT_ERROR);
        }
        return ApiRestResponse.error(MallExceptionEnum.REQUEST_ARGUMENT_ERROR.getCode(),list.toString());
    }
}
